import schema from 'validate'
const mobileValidate = new schema({
  mobile: {
    required: true,
    match: /^1[3-9]\d{9}$/,
    message: '手机号码不合法'
  }
})

const loginValidate = new schema({
  mobile: {
    required: true,
    match: /^1[3-9]\d{9}$/,
    message: '手机号码不合法'
  },
  code: {
    match: /^\d{6}$/,
    message: '验证码不通过'
  }
})

Page({
  data: {
    countDownVisible: false,
    timeData: {},
    /** 手机号 */
    mobile: '18200002233',
    /** 验证码 */
    code: '',
    /** 上一个页面 */
    fromUrl: ''
  },

  /** 获取页面参数 */
  onLoad(params) {
    console.log(params.redirectURL);
    this.data.fromUrl = params.redirectURL
  },

  /** 点击获取验证码 */
  async getCode() {
    const { mobile } = this.data
    const error = mobileValidate.validate({ mobile })
    if (error.length) {
      console.log(error[0].message);
      wx.utils.toast(error[0].message)
      return
    }
    let res = await wx.http({
      url: '/code',
      method: 'get',
      data: { mobile }
    })
    console.log(res.data.code);
    this.setData({
      countDownVisible: true
    })
  },

  /** 点击登录, 验证通过，保存token，跳转页面 */
  async login() {
    const { mobile, code } = this.data
    const error = loginValidate.validate({ mobile, code })
    if (error.length) {
      for (let i = 0; i < error.length; i++) {
        wx.utils.toast(error[i].message)
      }
      return
    }
    let res = await wx.http({
      url: '/login',
      method: 'post',
      data: { mobile, code }
    })
    /** 登录出错 */
    if (res.code !== 10000) {
      return wx.utils.toast(res.message)
    }
    /** 登录成功，保存 token */
    const app = getApp()
    app.setToken(res.data.token, res.data.refreshToken)
    if (this.data.fromUrl) {
      wx.reLaunch({ url: this.data.fromUrl })
    } else {
      wx.switchTab({ url: '/pages/index/index' })
    }
  },

  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
})
